package com.moto.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moto.Vo.UserLogVo;
import com.moto.entity.User;
import com.moto.entityDto.UpdateUser;
import com.moto.entityDto.UserLoginDto;
import com.moto.entityDto.UserRegisterDto;
import com.moto.interceptor.BaseContext;
import com.moto.interceptor.JwtProperties;
import com.moto.interceptor.JwtUtil;
import com.moto.result.Result;
import com.moto.service.IUserService;
import com.moto.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author hyf
 * @since 2023-08-28
 */
@RestController
@RequestMapping("/moto/User")
@Api(tags = "用户个人接口")
@Slf4j
@CrossOrigin("*")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    //注入redis
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 登录
     *
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<UserLogVo> login(@RequestBody UserLoginDto userLoginDto) {
        log.info("用户登录：{}", userLoginDto);

        System.out.println("用户登录");

        User user = userService.login(userLoginDto);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String userToken = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLogVo userLogVo = UserLogVo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .userToken(userToken)
                .build();
        //输出登录状态
        System.out.println(Result.success(userLogVo));
        return Result.success(userLogVo);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public Result<UserRegisterDto> register(@RequestBody UserRegisterDto userRegisterDto,HttpServletRequest request){
        log.info("用户注册：{}",userRegisterDto);
        String code = stringRedisTemplate.opsForValue().get("code");
        System.out.println("用户注册接口中的验证码为："+code);
        System.out.println("用户输入的验证码为："+userRegisterDto.getCode());
        if (!code.equals(userRegisterDto.getCode())){
            return Result.error("验证码错误");
        }
        //手机号是否重复
        int i = userService.findPhoneIsNull(userRegisterDto);
        if (i>0){
            return Result.error("手机号重复");
        }
        userService.registerUser(userRegisterDto);
        return Result.success();
    }

    /**
     * 用户查看个人头像和昵称
     */
    @GetMapping("/findUserIsHand")
    @ApiOperation("用户查看个人头像和昵称")
    public Result<User> findUserIsHand(){
        int id = Math.toIntExact(BaseContext.getCurrentId());
        System.out.println("经过jwt转换成的id为:"+id);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
        lqw.eq(User::getId,id);
        User one = userService.getOne(lqw);
        return Result.success(one);
    }

    /**
     * 用户修改个人信息接口
     */
    @PutMapping("updateUser")
    @ApiOperation("用户修改个人信息接口")
    public Result updateUser(@RequestBody UpdateUser updateUser){
        log.info("所需要修改的用户信息：{}",updateUser);
        Integer id = Math.toIntExact(BaseContext.getCurrentId());
        System.out.println("从token中解析的id为："+id);
        updateUser.setId(id);
        userService.updateUser(updateUser);
        return Result.success("修改信息成功");
    }


    /**
     * 创建验证码图片
     * @param
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("/validate")
    @ApiOperation("验证码接口")
    public String doGet(HttpServletResponse response) throws IOException {
        //创建一个画布,并指定画布的宽高和类型
        BufferedImage image =
                new BufferedImage(100,30,
                        BufferedImage.TYPE_3BYTE_BGR);

        //创建一支画笔
        Graphics2D g = (Graphics2D) image.getGraphics();

        //通过画笔设置画布的颜色
        g.setColor(new Color(
                255,    // 生成0-255的随机数
                255,    // 生成0-255的随机数
                255));   // 生成0-255的随机数
        g.fillRect(0,0,100,30);

        //设置字体,字形和大小
        Font font = new Font("楷体",Font.BOLD,25);
        g.setFont(font);

        //使用画笔在画布上写字
        //获取验证码
        String code = StringUtil.getCode();

        System.out.println("生成的验证码为："+code);

        //将验证码存入到session中
//        HttpSession session = request.getSession();
//        session.setAttribute("code",code);

        stringRedisTemplate.opsForValue().set("code",code);
        int x = 10;
        for(int i=0;i<code.length();i++){
            //设置画笔的颜色
            g.setColor(new Color(
                    new Random().nextInt(255),
                    new Random().nextInt(255),
                    new Random().nextInt(255)));
            //随机一个旋转角度(-60°-60°之间)
            int degree = new Random().nextInt(120)-60;
            //数学中π表示180°,Math.PI/180表示1度
            g.rotate(Math.PI/180*degree,x,20);
            g.drawString(code.charAt(i)+"",x,20);
            //向左旋转回来
            g.rotate(-Math.PI/180*degree,x,20);
            x += 20;
        }

        //画几条干扰线
        for(int i=0;i<5;i++){
            //设置画笔的颜色
            g.setColor(new Color(
                    new Random().nextInt(255),
                    new Random().nextInt(255),
                    new Random().nextInt(255)));
            int x1 = new Random().nextInt(100);
            int y1 = new Random().nextInt(30);
            int x2 = new Random().nextInt(100);
            int y2 = new Random().nextInt(30);
            g.drawLine(x1,y1,x2,y2);
        }

        //向前端浏览器页面输出画布
        //指定向前端页面的输出格式
        response.setContentType("image/png");
        //获取字节输出流
        OutputStream out = response.getOutputStream();
        //将image图片数据以png格式写出到out输出流中
        //再给前端浏览器页面进行返回
        ImageIO.write(image,"png",out);
        out.close();
        return code;
    }


}
